#include "physics/pvector.h"

#include <cmath>

#include <QDomDocument>

PVector::PVector(double x, double y)
{
    myX = x;
    myY = y;
}

PVector PVector::operator+(PVector vect) const {
    return PVector(myX + vect.myX, myY + vect.myY);
}

PVector PVector::operator-(PVector vect) const {
    return PVector(myX - vect.myX, myY - vect.myY);
}

PVector PVector::operator*(double c) const {
    return PVector(myX * c, myY * c);
}

PVector PVector::operator+=(PVector vect) const {
    return PVector(myX + vect.myX, myY + vect.myY);
}

PVector PVector::operator-=(PVector vect) const {
    return PVector(myX - vect.myX, myY - vect.myY);
}

PVector PVector::operator*=(double c) const {
    return PVector(myX * c, myY * c);
}

double PVector::mult(PVector vect) const {
    return myX * vect.myX + myY * vect.myY;
}

double PVector::getX() const {
    return myX;
}

void PVector::setX(double x) {
    myX = x;
}

double PVector::getY() const {
    return myY;
}

void PVector::setY(double y) {
    myY = y;
}

double PVector::distance(PVector vect) const {
    return sqrt((myX - vect.myX) * (myX - vect.myX) + (myY - vect.myY) * (myY - vect.myY));
}

double PVector::distanceSqr(PVector vect) const {
    return (myX - vect.myX) * (myX - vect.myX) + (myY - vect.myY) * (myY - vect.myY);
}

double PVector::length() const {
    return sqrt((myX) * (myX) + (myY) * (myY));
}

void PVector::serialize(QDomDocument *doc, QDomElement *e) const {
    QDomElement x = doc->createElement("x");
    QDomElement y = doc->createElement("y");

    QDomNode x_v = doc->createTextNode(QString("%1").arg(myX));
    x.appendChild(x_v);

    QDomNode y_v = doc->createTextNode(QString("%1").arg(myY));
    y.appendChild(y_v);

    e->appendChild(x);
    e->appendChild(y);
}

PVector PVector::deserialize(QDomNode node) {
    PVector v;
    QDomElement elem = node.toElement();
    QDomNode n = elem.firstChild();
    double x = 0;
    double y = 0;
    while (!n.isNull()) {
        QString name = n.toElement().tagName();
        if (name == "x") {
            x = n.firstChild().toText().data().toDouble();
        } else if (name == "y") {
            y = n.firstChild().toText().data().toDouble();
        }
        n = n.nextSibling();
    }
    v.myX = x;
    v.myY = y;
    return v;
}
